package net.NingXiaRuiTai.ShortChain.server.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import net.NingXiaRuiTai.ShortChain.config.OSSConfig;
import net.NingXiaRuiTai.ShortChain.server.FileService;
import net.NingXiaRuiTai.ShortChain.utils.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.pattern.PathPatternParser;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @Description
 * @Author oversea
 * @Date 2025/2/3
 */
@Service
@Slf4j
public class FileServiceImpl implements FileService {
    @Autowired
    private OSSConfig ossConfig;


    @Override
    public String uploadUserImag(MultipartFile file) {
        String bucketName = ossConfig.getBucketName();
        String endpoint = ossConfig.getEndpoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //获取文件的名称：xxx.jpg
        String originalFilename = file.getOriginalFilename();


        //jdk8语法获取日期格式
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        //拼接文件存储路径

        String formatData = dateTimeFormatter.format(now);
        String newFileName = CommonUtil.generateUUID();
        String extension=originalFilename.substring(originalFilename.lastIndexOf("."));

        //在oss的bucket上创建user文件夹
        String objectName = "user/"+formatData+"/"+newFileName+extension;
        //上传文件
        try {
            PutObjectResult putObjectResult = ossClient.putObject(bucketName, objectName, file.getInputStream());
            if (putObjectResult!=null){
                //拼接文件访问路径
                String url = "https://"+bucketName+"."+endpoint+"/"+objectName;
                return url;
            }



        }catch (Exception e){
            log.error("上传文件异常：{}",e.getMessage());
        }finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }


        return null;
    }
}
